﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using PDO.Utilities;

namespace PDO.DataPersistence.Core
{
    internal class DataObjectCacheItem
    {
        private string _key;
        private DataSet _dataSet;


        public DataObjectCacheItem(string key, DataSet ds)
        {
            _key = key;
            _dataSet = ds;
        }

        public string Key
        {
            get { return _key; }
            set { _key = value; }
        }

        public DataSet DataSet
        {
            get { return _dataSet; }
            set { _dataSet = value; }
        }
    }

    internal class DataObjectCache : ExpirableCache<string, DataObjectCacheItem>
    {
        protected override string GetKeyForItem(DataObjectCacheItem item)
        {
            return item.Key;
        }
    }

    public static class CacheManager
    {
        private static DataObjectCache _cache;


        private const string MAX_CACHED_ROWS = "CIS.DataCache.MaxCachedRows";
        private const int MAX_CACHED_ROWS_DEFAULT = 100;

        private static int _maxCachedRows = -1;


        static CacheManager()
        {
            _cache = new DataObjectCache();
        }

        public static bool Contains(string key)
        {
            return _cache.Contains(key);
        }

        public static DataSet Get(string key)
        {
            // redundant  if (_cache.Contains(key))
            {
                return _cache[key].DataSet ;
            }

            return null;
        }

        public static void Put(string key, DataSet ds)
        {
            _cache.Add(new DataObjectCacheItem(key, ds));
        }

        public static void Remove(string key)
        {
            _cache.Remove(key);
        }


        public static int MaxCachedRows
        {
            get 
            {
                if (_maxCachedRows < 0)
                {
                    _maxCachedRows = ConfigurationHelper.ReadConfigurationStringAsInt(MAX_CACHED_ROWS, MAX_CACHED_ROWS_DEFAULT);

                }
                return _maxCachedRows; 
            }

            set { _maxCachedRows = value; }
        }
    }
}
